<template>
  <div class="page-container">
    <el-dialog title="提示" v-model="dialogVisible" width="30%">
      <span>确认要删除该条数据吗?</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleDelete">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <div class="container">
      <!-- 左侧树状结构，使用封装的组件 -->
      <catalog ref="categoryTreeRef"
               :fetch="false"
               :api-prefix="'moduleCatalog'"
               :current-node-key="searchObject.selectKey"
               :default-expanded-keys="searchObject.treeKeys"
               v-model="selectedParentNode"
               @node-click="handleCategoryNodeClick"
               title="模型分类"
               show-node-actions
      />

      <!-- 右侧内容区 -->
      <div class="content-container">
        <div class="search">
          <el-form label-width="80px" :model="searchObject" ref="searchForm">
            <el-row>
              <el-col :span="6" style="padding: 0 8px;">
                <el-form-item label="模型名称" prop="name">
                  <el-input v-model="searchObject.name" placeholder="模型名称" name="name" @keyup.enter="search">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6" style="padding: 0 8px;">
                <el-form-item label="数据表名" prop="tableName">
                  <el-input v-model="searchObject.tableName" placeholder="数据表名" name="tableName" @keyup.enter="search">
                  </el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12" style="padding: 0 10px;">
                <el-row type="flex" justify="end">
                  <el-button type="primary" @click="search">搜索</el-button>
                  <el-button plain @click="clearSearch">清除条件</el-button>
                </el-row>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div class="data-content">
          <div class="tool-add">
            <el-button type="primary" @click="goAddView">新增</el-button>
          </div>

          <el-table v-loading="loading" :data="pageData.data" @sort-change="changeTableSort"
                    style="width: 100%;font-size: 12px;">
            <el-table-column label="序号" type="index" width="50">
            </el-table-column>
            <el-table-column label="模型名称" prop="name" width="200">
            </el-table-column>
            <el-table-column label="数据表名" prop="tableName" width="200">
            </el-table-column>
            <el-table-column label="描述" prop="note" width="300">
            </el-table-column>
            <el-table-column label="添加时间" prop="addDate" width="160" sortable="custom">
            </el-table-column>
            <el-table-column width="250" align="center" fixed="right" label="操作">
              <template #default="scope">
                <el-button text class="operation_bt" :icon="Edit" type="primary" @click="editView(scope.row)">编辑
                </el-button>
                <el-button text class="operation_bt" :icon="Refresh" type="info" @click="updateModelTable(scope.row)">更新表
                </el-button>
                <el-button text :icon="Delete" class="operation_bt" type="danger" style="cursor: pointer;"
                          @click="deleteData(scope.row)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="page">
            <el-pagination background :current-page="searchObject.no" :page-sizes="[10, 20, 30, 50, 100]"
                          :page-size="pageData.size" :pager-count="5"
                          layout="total, sizes, prev, pager, next, jumper" :page-count="pageData.totalPage"
                          :total="pageData.total" @size-change="sizeChange" @current-change="pageChange">
            </el-pagination>
          </div>
        </div>
      </div>
    </div>

    <!-- 使用模型表单组件 -->
    <model-form
      v-if="showAddModelDialog"
      v-model:visible="showAddModelDialog"
      :model="currentModel"
      :is-editing="isEditing"
      :category-options="categoryOptions"
      :current-category="currentCategory"
      @saved="loadModels"
    />
  </div>
</template>

<script setup>
import { Delete, Edit, Refresh } from '@element-plus/icons-vue'
import { defineStore } from 'pinia'
import { useDelete } from "@/utils/useDelete"
import { useView } from "@/utils/useView"
import { onMounted, ref, computed } from "vue"
import { usePageData } from "@/uses/usePageData.js"
import { useRouter } from "vue-router"
import { ElMessage, ElMessageBox } from 'element-plus'
import Catalog from "@/components/catalog.vue"
import ModelForm from '@/views/pages/chat/components/ModelForm.vue'
import http from '@/utils/request'

const router = useRouter()

const searchForm = ref()
const searchStore = defineStore('modelStore', {
  state: () => {
    return {
      searchObject: {
        no: 1,
        size: 30,
        sortField: "addDate",
        sortMethod: "desc",
        name: null,
        tableName: null,
        catalog: null,
        treeKeys: null,
        selectKey: null,
        categoryId: null
      }
    }
  }
})

const { searchObject } = searchStore()

const clearSearch = () => {
  searchObject.name = null
  searchObject.tableName = null
  searchObject.catalog = null
}

const {
  pageData,
  sizeChange,
  pageChange,
  search,
  changeTableSort,
  loading
} = usePageData("module_list", searchObject)

const { dialogVisible, deleteData, handleDelete } = useDelete("/module/delete", search)
const { showView, addView } = useView()

// 引用分类树组件和相关数据
const categoryTreeRef = ref(null)
const selectedParentNode = ref(null)

// 模型表单相关
const showAddModelDialog = ref(false)
const isEditing = ref(false)
const currentModel = ref({})
const currentCategory = ref(0)

// 构建级联选择器的选项
const categoryOptions = computed(() => {
  // 这里可以根据需要构建选项，暂时返回空数组
  return []
})

onMounted(() => {
  if (searchObject.catalog) {
    selectedParentNode.value = searchObject.catalog
  }
})

const goAddView = async () => {
  isEditing.value = false
  currentModel.value = {}
  
  // 如果有选中的分类，设置为当前分类
  if (searchObject.catalog) {
    currentCategory.value = searchObject.catalog
  }
  
  showAddModelDialog.value = true
}

// 处理分类树节点点击
const handleCategoryNodeClick = (data) => {
  // 记录选中的节点用于筛选
  selectedParentNode.value = data

  searchObject.treeKeys = [data.id]
  searchObject.selectKey = data.id
  // 更新搜索条件，根据选中的分类节点筛选数据
  searchObject.catalog = data.id // 当点击"全部"节点时，catalog将为null
  searchObject.no = 1
  currentCategory.value = data.id
  search()
}

// 编辑模型
const editView = (model) => {
  isEditing.value = true
  currentModel.value = model
  showAddModelDialog.value = true
}

// 更新模型数据表
const updateModelTable = async (model) => {
  try {
    const result = await ElMessageBox.confirm(
      `确定要更新模型 "${model.name}" 的数据表结构吗？这将根据模型字段定义更新对应的数据库表。`,
      '确认更新',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    if (result === 'confirm') {
      // 构建更新数据表的参数
      const updateTableData = {
        id: model.id
      }

      const res = await http.post('/module/updateTable', updateTableData)

      if (res.code === 200) {
        ElMessage.success('数据表结构更新成功')
      } else {
        ElMessage.error(res.message || '数据表更新失败')
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新数据表出错:', error)
      ElMessage.error('更新失败，请检查网络连接')
    }
  }
}

// 加载模型数据
const loadModels = () => {
  search()
}
</script>

<style scoped lang="scss">
.page-container {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
}

.container {
  display: flex;
  height: 100%;
  overflow: hidden;
  flex: 1;
}

.content-container {
  flex: 1;
  padding: 10px;
  overflow: hidden;
  min-width: 0;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.search {
  margin-bottom: 10px;
}

.data-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  border: none;
}

.tool-add {
  margin-bottom: 10px;
}

.page {
  margin-top: 15px;
  display: flex;
  justify-content: center;
  padding-bottom: 15px;
}

.operation_bt {
  margin: 0 2px;
}

:deep(.el-table) {
  --el-table-border-color: #dcdfe6;
  flex: 1;
  overflow: auto;
}

:deep(.el-dialog__body) {
  padding-top: 10px;
  padding-bottom: 10px;
}
</style>

